<template>
  <div class="employees-container">
    <div class="app-container">
      <PageTools>
        <template #left>
          总记录条数:{{ total }}条
        </template>
        <el-button v-if="check('POINT-USER-Import')" type="primary" size="small" @click="$router.push('/import')">导入</el-button>
        <el-button v-check="'POINT-USER-EXPORT'" type="success" size="small" @click="exportExcel">导出</el-button>
        <el-button v-if="check('POINT-USER-ADD')" type="warning" size="small" @click="showDialog = true">新增员工</el-button>
      </PageTools>
      <el-card>
        <el-table
          v-loading="loading"
          :data="list"
          style="width: 100%"
          border
        >
          <el-table-column
            type="index"
            :index="indexMethod"
            label="序号"
            width="100"
            sortable
            align="center"
          />
          <el-table-column
            prop="username"
            label="姓名"
            width="100"
            sortable
            align="center"
          />
          <el-table-column
            label="头像"
            align="center"
          >
            <template v-slot="{row}">
              <img
                v-imgerror="require('@/assets/common/head.jpg')"
                :src="row.staffPhoto"
                width="60px"
                height="60px"
                style="border-radius: 50%; object-fit:cover"
                @click="showQrCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="mobile"
            label="手机号"
            width="180"
            sortable
            align="center"
          />
          <el-table-column
            prop="workNumber"
            label="工号"
            sortable
            align="center"
          />
          <!-- <el-table-column
            prop="formOfEmployment"
            label="聘用形式"
            sortable
            align="center"
          >
            <template v-slot="{row}">
              {{ hireType.find(item => item.id == row.formOfEmployment).value }}
            </template>
          </el-table-column> -->
          <el-table-column
            label="聘用形式"
            align="center"
            prop="formOfEmployment"
            :formatter="formatEmployment"
          />
          <el-table-column
            prop="departmentName"
            label="部门"
            sortable
            align="center"
          />
          <el-table-column
            label="入职时间"
            sortable
            align="center"
          >
            <template v-slot="{row}">
              <span>{{ row.timeOfEntry | time }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="账户状态"
            sortable
            align="center"
          >
            <template>
              <!-- {{ row.enableState === 1? '可用':'禁用' }} -->
              <!-- <el-switch
                :value="row.enableState === 1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              /> -->
              {{ '可用' }}
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="250"
            align="center"
          >
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="showRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- // 分页 -->
        <el-row type="flex" justify="end" style="margin-top: 10px">
          <el-pagination
            :current-page="page"
            :page-size="size"
            layout="total, prev, pager, next"
            :total="total"
            @current-change="changeFn"
          />
        </el-row>
      </el-card>
      <!-- // 新增员工Dialog组件 -->
      <AddEmployee :show-dialog.sync="showDialog" />
      <!-- // 图片生成二维码弹窗 -->
      <el-dialog title="二维码" :visible.sync="showCodeDialog">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <!-- // 分配角色Dialog组件 -->
      <AssignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { getEmployeeDetailList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/AddEmployee'
import AssignRole from './components/AssignRole'
import moment from 'moment'
import Qrcode from 'qrcode'
export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      // 员工列表
      list: [],
      // 总计条数
      total: 0,
      size: 10,
      page: 1,
      loading: false,
      hireType: EmployeeEnum.hireType,
      showDialog: false, // 控制新增员工弹窗
      showCodeDialog: false, // 控制二维码弹窗
      showRoleDialog: false, // 控制角色弹窗
      userId: '' // 当前员工ID
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async getEmployeeList() {
      this.loading = true
      const data = await getEmployeeDetailList(this.page, this.size)
      // console.log(data)
      this.list = data.rows
      this.total = data.total
      this.loading = false
    },
    // 当curentpage 页码改变的时候触发 重新发送请求获取数据
    changeFn(page) {
      this.page = page
      this.getEmployeeList()
    },
    // 序号显示为下标
    indexMethod(index) {
      return (this.page - 1) * this.size + index + 1
    },
    formatEmployment(row, column, cellValue, index) {
      if (cellValue === null) {
        return '其他'
      }
      return this.hireType.find(item => item.id === +cellValue).value
    },
    // 删除员工
    async delEmployee(id) {
      try {
        await this.$confirm('您确定删除吗?', '温馨提示', {
          type: 'warning'
        })
      } catch {
        return
      }
      // 发请求删除员工
      await delEmployee(id)
      // console.log(data)
      // 提示消息
      this.$message.success('删除成功')
      // 发送请求重新获取数据
      if (this.list.length === 1 && this.list.length > 0) {
        this.page--
      }
      this.getEmployeeList()
    },
    // 导出功能
    exportExcel() {
      import('@/utils/Export2Excel').then(async excel => {
        const obj = {
          '入职日期': 'timeOfEntry',
          '手机号': 'mobile',
          '姓名': 'username',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '聘用形式': 'formOfEmployment',
          '部门': 'departmentName'
        }
        // Object.keys  接收一个对象参数, 可以拿到对象里面所有的key,返回一个数组
        // Object.values 接收一个对象参数, 可以拿到对象里面所有的value,返回一个数组
        const tHeader = Object.keys(obj)

        // 发送请求获取员工列表数据
        const { rows } = await getEmployeeDetailList(1, 1000)
        const data = rows.map(item => {
          const arr = []
          Object.values(obj).forEach(k => {
            if (k === 'timeOfEntry' || k === 'correctionTime') {
              item[k] = moment(item[k]).format('YYYY/MM/DD')
            } else if (k === 'formOfEmployment') {
              item[k] = item[k] === 1 ? '正式' : '非正式'
            }
            arr.push(item[k])
          })
          return arr
        })
        console.log(tHeader, data)
        excel.export_json_to_excel({
          // header: excel表头
          // data: 需要写入excel的数据
          // filename： 保存的文件名
          // autoWidth: excel的列是否自动设置宽度
          // bookType: 后缀名
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
      })
    },
    // 头像二维码弹窗事件
    async showQrCode(photo) {
      this.showCodeDialog = true
      // dialog为true的时候dom还没有更新，第一次点击头像的时候会报错并没有显示二维码
      await this.$nextTick()
      Qrcode.toCanvas(this.$refs.myCanvas, photo)
    },
    // 控制分配角色弹窗
    showRole(id) {
      this.showRoleDialog = true
      this.userId = id
    }
  }
}
</script>

<style>

</style>

